# -*- coding: utf-8 -*-
# =============================================================================
#     FileName:
#         Desc:
#       Author: GGA
#        Email:
#     HomePage:
#      Version: 1.0.1
#   LastChange: 2020-12-20
#      History:
# =============================================================================
import subprocess
from utils.logger_helper import LoggerHelper

logger = LoggerHelper.get_logger()


class LocalLinuxHelper(object):
    @classmethod
    def get_server_host_name(cls):
        """
        获取并设置服务器实例名称
        """
        try:
            re_val, host_name = subprocess.getstatusoutput('hostname')
            return host_name
        except Exception as ex:
            print("获取服务器名称失败：{}".format(str(ex)))
            return None

    @classmethod
    def get_process_count_by_keys(cls, process_keys):
        try:
            grep_comm = " | grep -v 'grep'"
            for key_item in process_keys:
                grep_comm += " | grep '" + str(key_item).replace("'", "") + "'"
            check_comm = 'ps -ef ' + grep_comm + ' | wc -l'
            re_val, process_count = subprocess.getstatusoutput(check_comm)
            return int(process_count)
        except Exception as ex:
            logger.info("检查进程是否运行失败，异常为：{}".format(str(ex)))
            return None

    @classmethod
    def is_last_process_running(cls, process_keys):
        """
        检查上一次脚本是否运行完成，如果未完成，则当前执行进程数超过2
        """
        if cls.get_process_count_by_keys(process_keys) > 2:
            return True
        else:
            return False

    @classmethod
    def get_sub_process_id(cls, process_id):
        """
        根据主进程ID获取子进程编号列表
        :param process_id:
        :return:
        """
        cmd = """ ps -ef|awk  '{if($3==""" + str(process_id) + """) print $2}'|sort | uniq """
        re_val, sub_process_ids = subprocess.getstatusoutput(cmd)
        return sub_process_ids
